﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Net;
using System.Text;

namespace ArcGisMapDesktop.Common
{
    public class IPScanerHelper
    {
        public static void GetHostInfo(out string hostName, out string ip, out string mac)
        {
            //获得主机名
            hostName = Dns.GetHostName();
            //获取IP
            ip = GetIP(hostName);
            mac = string.Empty;
            //获取本机mac
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM   Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {
                if (mo["IPEnabled"].ToString() == "True")
                    mac = mo["MacAddress"].ToString();
            }
            mac = MD5Helper.GetMD5Encode(mac);
        }

        private static string GetIP(string hostName)
        {
            string ipv4 = String.Empty;
            foreach (IPAddress ip in Dns.GetHostAddresses(hostName))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            if (ipv4 != String.Empty)
            {
                return ipv4;
            }
            // 利用 Dns.GetHostEntry 方法，由获取的 IPv6 位址反查 DNS 纪录，
            // 再逐一判断何者为 IPv4 协议，即可转为 IPv4 位址。
            foreach (IPAddress ip in Dns.GetHostEntry(hostName).AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            return ipv4;
        }
    }
}
